package main

import (
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"os"
	"time"
)

var (
	url string
)

func init() {
	now := time.Now().Format("0102")
	host, err := os.Hostname()
	url = fmt.Sprintf("./home/%v/%v/", now, host)
	err = os.MkdirAll(url, 0644)
	if err != nil {
		fmt.Println("mkdir url failed")
		return
	}
}

func main() {
	fmt.Println("请访问下面的链接:(运行中请勿关闭)")
	showIp()
	http.HandleFunc("/", uploadFileHandler)
	http.Handle("/file/", http.StripPrefix("/file/", http.FileServer(http.Dir("home"))))
	http.ListenAndServe(":8080", nil)
}
func uploadFileHandler(w http.ResponseWriter, r *http.Request) {
	/**/
	htmlFile := `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>多平台局域网内文件互传</title>
</head>
<body style="text-align: center;"> 
    <h1>多平台局域网内文件互传</h1>
    <br>
    <br>
    <form action="UploadFile.ashx" method="post" enctype="multipart/form-data">
    <input type="file" name="fileUpload" />
    <input type="submit" name="上传文件">
    </form>
        <br>
    <br>
        <br>
    <br>
    <a href="/file">文件下载</a>
</body>
</html>
 `
	fmt.Fprintln(w, htmlFile)
	if r.Method == "POST" {
		file, handler, err := r.FormFile("fileUpload") //name的字段
		if err != nil {
			fmt.Println(err)
			return
		}
		defer file.Close()
		fileBytes, err := ioutil.ReadAll(file)
		if err != nil {
			fmt.Println(err)
			return
		}
		newFile, err := os.OpenFile(url+handler.Filename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
		//newFile, err := os.Create("./home/banapy/tmp/" + handler.Filename)
		if err != nil {
			fmt.Println(err)
			return
		}
		defer newFile.Close()
		if _, err = newFile.Write(fileBytes); err != nil {
			fmt.Println(err)
		}
		fmt.Println(" upload successfully:")
		w.Write([]byte("SUCCESS"))
	}
}
func showIp() {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	for _, address := range addrs {
		// 检查ip地址判断是否回环地址
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				fmt.Println(ipnet.IP.String() + ":8080")
			}
		}
	}
}
